package com.leenmvc.core.web.controller;

import com.leenmvc.core.annotation.Note;
import com.leenmvc.core.base.BaseController;
import com.leenmvc.core.security.User;
import com.leenmvc.core.security.entity.core.SysDept;
import com.leenmvc.core.security.service.core.SysDeptService;
import com.leenmvc.core.utils.collection.TreeUtils;
import com.leenmvc.core.base.result.Result;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("system/sysDept")
public class SysDeptController extends BaseController<SysDept> {

    @Autowired
    private SysDeptService sysDeptService;

    @GetMapping("getDeptList")
    @RequiresPermissions("system:sysDept:getDeptList")
    @Note("获取部门管理的信息数据")
    public Result<List<SysDept>> getDeptList(@RequestParam(required = true) Map<String, Object> params) {
        Long deptId = User.getUser().getDeptId();
        params.put("deptIdList", listBySqlKey("getSubDeptIdList", "id", deptId));
        //查询部门列表
        List<SysDept> deptList = listBySqlKey("getDeptList", params);
        for (SysDept sysDept : deptList) {
            Long topId = sysDeptService.findTopId(sysDept);
            sysDept.setTopId(topId);
        }
        deptList = TreeUtils.build(deptList);
        return new Result().ok(deptList);
    }

    @GetMapping("{id}")
    @RequiresPermissions("system:sysDept:info")
    @Note("根据ID获取部门信息")
    public Result<SysDept> getById(@PathVariable("id") Long id) {
        List<SysDept> list = sysDeptService.listBySqlKey("getById", "id", id);
        Long topId = null;
        SysDept sysDept = null;
        if (null != list) {
            sysDept = list.get(0);
            for (SysDept dept : list) {
                //如果上级Id不等于空
                topId = sysDeptService.findTopId(dept);
            }
        }
        sysDept.setTopId(topId);
        return new Result().ok(sysDept);
    }

    @DeleteMapping("{id}")
    @RequiresPermissions("system:sysDept:del")
    @Note("删除部门表记录的信息")
    public Result delById(@PathVariable("id") Long id) {
        sysDeptService.delById(id);
        return new Result();
    }


}
